package com.song.serprovider;

import com.song.enumeration.RpcError;
import com.song.exception.RpcException;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 此前提需要  通过自动扫描注解 向服务注册表添加本地服务
 * 默认的服务注册表，保存 服务器的本地服务
 */
@Slf4j(topic = "c.ServiceProviderImpl")
public class ServiceProviderImpl implements ServiceProvider {
    private static final Map<String, Object> serviceMap = new ConcurrentHashMap<>();
    private static final Set<String> registeredService = ConcurrentHashMap.newKeySet();

    @Override
    public <T> void addServiceProvider(T service, String serviceName) {
        if(registeredService.contains(serviceName)) return;
        registeredService.add(serviceName);
        serviceMap.put(serviceName, service);
        log.info("向接口：{} 注册服务：{}", service.getClass().getInterfaces(), serviceName);//interfaceName=com.song.api.HelloService, methodName=hello
    }

    @Override
    public Object getServiceProvider(String serviceName) {
        Object service = serviceMap.get(serviceName);
        if(service == null) {
            throw new RpcException(RpcError.SERVICE_NOT_FOUND);
        }
        return service;
    }
}
